from flask import jsonify
from datetime import datetime


def my_job(*options):
    # with scheduler.app.app_context():
    #     CronTab.query.filter_by(cron_task_id=datas["task_id"]).first()
    print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print(options)


"""
添加data类型定时任务
{
	"task_id": "2",
	"run_time": "2020-8-12 12:03:00",
	"trigger_type": "date"
}
添加interval类型定时任务
{
	"task_id": "5",
	"interval_time": 10,
	"trigger_type": "interval"
}
添加cron类型定时任务
{
	"task_id": "5",
	"run_time": {
		"day_of_week": "2",
		"hour": "16",
		"minute": "19",
		"second": "00"
	},
	"trigger_type": "cron"
}
"""
from extensions.init_scheduler import scheduler


# 新增job
def add_cron(task_id, trigger_type, interval_time, job):
    seconds = int(interval_time)
    if seconds <= 0:
        raise TypeError('请输入大于0的时间间隔！')
    scheduler.add_job(func=my_job,
                      trigger=trigger_type,
                      seconds=seconds,
                      replace_existing=True,
                      coalesce=True,
                      id=task_id,
                      args=[task_id, job])
    return jsonify(msg="新增任务成功")


# 暂停
# @scheduler_bp.route('/pause/<task_id>', methods=['GET'])
def pause_job(task_id):
    response = {'status': False}
    try:
        scheduler.pause_job(task_id)
        response['status'] = True
        response['msg'] = "job[%s] pause success!" % task_id
    except Exception as e:
        response['msg'] = str(e)
    return jsonify(response)


# 启动
# @scheduler_bp.route('/resume/<task_id>', methods=['GET'])
def resume_job(task_id):
    response = {'status': False}
    try:
        scheduler.resume_job(task_id)
        response['status'] = True
        response['msg'] = "job[%s] resume success!" % task_id
    except Exception as e:
        response['msg'] = str(e)
    return jsonify(response)


# 删除
# @scheduler_bp.route('/remove/<task_id>', methods=['GET'])
def remove_job(task_id):
    response = {'status': False}
    try:
        scheduler.remove_job(task_id)
        response['status'] = True
        response['msg'] = "job[%s] remove success!" % task_id
    except Exception as e:
        response['msg'] = str(e)
    return jsonify(response)

# 编辑逻辑与新增大致相同，编辑时如果传的task_id 任务表中已存在，那么会直接替换原来的task_id。

# 查job信息，获取的信息包括了job类型和执行时间，可以打印出来结果再根据自己的代码逻辑进行编写
# 查看所有的job信息
# ret_list = scheduler.get_jobs()
#  查看指定的job信息
# ret_list = scheduler.get_job(jid)
#
# def reg_schedule_bp(app):
#     app.register_blueprint(scheduler_bp)
